import 'dart:async';

import 'package:demo/constants/platform_key.dart';
import 'package:flutter/foundation.dart';
import 'package:fluwx/fluwx.dart';

export "package:fluwx/fluwx.dart" show WeChatScene, WeChatImage;

typedef OnWeChatResponseEventCallback = void Function(dynamic response);

@immutable
class ShareBean {
  final String title;
  final String description;
  final WeChatImage imgUrl;
  final String shareUrl;

  const ShareBean({this.title = "", this.description = "", required this.imgUrl, this.shareUrl = ""});
}

class WxSdkUtils {
  /// 工厂模式
  factory WxSdkUtils() => _getInstance();

  /// 单例
  static WxSdkUtils get instance => _getInstance();
  static WxSdkUtils? _instance;

  StreamSubscription? _weChatEventHandler;

  WxSdkUtils._internal();

  static WxSdkUtils _getInstance() => _instance ??= WxSdkUtils._internal();

  /// 初始化sdk
  Future<void> initWXSDk() async {
    await registerWxApi(
      appId: SHARE_WX_APP_ID,
      universalLink: ShARE_WX_IOS_LINKS,
    );
  }

  /// 是否安装了微信
  Future<bool> get isInstallWechat async => await isWeChatInstalled;

  /// 发起微信登录(非静默授权)
  Future<bool> get weChatAuth async => await sendWeChatAuth(scope: "snsapi_userinfo", state: "hengqijiaoyu_App");

  /// 配置监听器
  void setWeChatEventHandler(OnWeChatResponseEventCallback callback) {
    _weChatEventHandler = weChatResponseEventHandler.distinct((a, b) => a == b).listen(callback);
  }

  void disposeWechatEventHandler() {
    _weChatEventHandler?.cancel();
  }

  /// 分享
  Future<bool> share(WeChatScene scene, ShareBean shareBean) async {
    return await shareToWeChat(
      WeChatShareWebPageModel(
        shareBean.shareUrl,
        title: shareBean.title,
        description: shareBean.description,
        thumbnail: shareBean.imgUrl,
        scene: scene,
      ),
    );
  }
}
